package com.lamer.console.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lamer.console.base.entity.Param;
import com.lamer.console.base.service.IParamService;
import com.lamer.console.common.api.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/blog")
public class ParamController {

    @Autowired
    private IParamService paramService;

    @GetMapping
    @RequestMapping("/param/page/")
    public ApiResult<Page<Param>> getPage(@RequestParam("search") String search) {
        JSONObject jsonObject = JSON.parseObject(search);
        Integer number = jsonObject.getInteger("page_number");
        Integer size = jsonObject.getInteger("page_size");
        String code = jsonObject.getString("code");
        String name = jsonObject.getString("name");
        String value = jsonObject.getString("value");

        LambdaQueryWrapper<Param> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(code)) queryWrapper.like(Param::getCode, code);
        if(StringUtils.isNotBlank(name)) queryWrapper.like(Param::getName, name);
        if(StringUtils.isNotBlank(value)) queryWrapper.like(Param::getValue, value);

        Page<Param> page = paramService.page(new Page<>(number, size), queryWrapper);
        return ApiResult.success(page);
    }

    @GetMapping("/param/{id}")
    public ApiResult<Param> getParam(@PathVariable("id") int id) {
        Param param = paramService.getById(id);
        return param == null ? ApiResult.failed() : ApiResult.success(param);
    }

    @PostMapping("/param/")
    public ApiResult<Param> postParam(@RequestBody Param param){
        boolean flag = paramService.save(param);
        return flag ? ApiResult.success() : ApiResult.failed();
    }

    @PutMapping("/param/")
    public ApiResult<Param> putParam(@RequestBody Param param){
        boolean flag = paramService.updateById(param);
        return flag ? ApiResult.success() : ApiResult.failed();
    }

    @DeleteMapping("/param/list/")
    public ApiResult<Param> deleteParam(@RequestParam("ids") int[] ids){
        List<Integer> collect = Arrays.stream(ids).boxed().collect(Collectors.toList());
        boolean flag = paramService.removeByIds(collect);
        return flag ? ApiResult.success() : ApiResult.failed();
    }

}
